package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.HotelCatalog;
import cn.wolfcode.trip.base.domain.HotelContent;
import cn.wolfcode.trip.base.mapper.HotelCatalogMapper;
import cn.wolfcode.trip.base.mapper.HotelContentMapper;
import cn.wolfcode.trip.base.query.HotelQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IHotelCatalogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HotelCatalogServiceImpl implements IHotelCatalogService {

    @Autowired
    private HotelCatalogMapper hotelCatalogMapper;
    @Autowired
    private HotelContentMapper hotelContentMapper;

    @Override
    public PageInfo<HotelCatalog> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<HotelCatalog> list = hotelCatalogMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public String listById(Long id) {
        return hotelContentMapper.selectByPrimaryKey(id).getContent();
    }

    @Override
    public HotelCatalog get(Long id) {
        HotelContent hotelContent = hotelContentMapper.selectByPrimaryKey(id);
        HotelCatalog hotelCatalog = hotelCatalogMapper.selectByPrimaryKey(id);
        hotelCatalog.setHotelContent(hotelContent);
        return hotelCatalog;
    }

    @Override
    public PageInfo list(QueryObject qo, Long hotelId) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<HotelCatalog> list = hotelCatalogMapper.listAll(qo,hotelId);
        return new PageInfo<>(list);
    }

    @Override
    public List<HotelCatalog> selectByRecommend(HotelQueryObject qo) {
        return hotelCatalogMapper.selectByRecommend(qo);
    }

    @Override
    public void saveOrUpdate(HotelCatalog entity) {
        if(entity.getSquence() == null){
            Integer sequence = hotelCatalogMapper
                    .selectSquenceByhotelId(entity.getHotel().getId());

            if(sequence == null){
                sequence = 0;
            }
            entity.setSquence(sequence + 1);
        }
        HotelContent hotelContent = entity.getHotelContent();
        if(entity.getId() == null){
            hotelCatalogMapper.insert(entity);
            hotelContent.setId(entity.getId());
            hotelContentMapper.insert(hotelContent);
        }else {
            hotelCatalogMapper.updateByPrimaryKey(entity);
            hotelContent.setId(entity.getId());
            hotelContentMapper.updateByPrimaryKey(hotelContent);
        }
    }
}
